package com.example.smssender;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.chip.Chip;
import java.util.ArrayList;
import java.util.List;

/**
 * 联系人预览列表适配器（主页显示前几个联系人）
 */
public class ContactPreviewAdapter extends RecyclerView.Adapter<ContactPreviewAdapter.ViewHolder> {
    
    private List<Contact> contacts;
    private OnContactDeleteListener listener;
    private static final int MAX_PREVIEW_COUNT = 5; // 最多显示5个预览
    
    public interface OnContactDeleteListener {
        void onContactDelete(Contact contact);
    }
    
    public ContactPreviewAdapter(List<Contact> contacts, OnContactDeleteListener listener) {
        this.contacts = contacts;
        this.listener = listener;
    }
    
    public void updateContacts(List<Contact> contacts) {
        this.contacts = contacts != null ? contacts : new ArrayList<>();
        notifyDataSetChanged();
    }
    
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_contact_preview, parent, false);
        return new ViewHolder(view);
    }
    
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Contact contact = contacts.get(position);
        if (contact == null) {
            return;
        }
        
        String displayText = contact.getName() != null ? contact.getName() : "未知";
        if (contact.getPhoneNumber() != null && !contact.getPhoneNumber().isEmpty()) {
            // 只显示手机号后4位
            String phone = contact.getPhoneNumber();
            if (phone.length() > 4) {
                displayText += " (" + phone.substring(phone.length() - 4) + ")";
            } else {
                displayText += " (" + phone + ")";
            }
        }
        
        holder.chip.setText(displayText);
        
        // 删除图标点击事件
        holder.chip.setOnCloseIconClickListener(v -> {
            if (listener != null) {
                listener.onContactDelete(contact);
            }
        });
    }
    
    @Override
    public int getItemCount() {
        if (contacts == null) {
            return 0;
        }
        // 最多显示5个预览
        return Math.min(contacts.size(), MAX_PREVIEW_COUNT);
    }
    
    static class ViewHolder extends RecyclerView.ViewHolder {
        Chip chip;
        
        ViewHolder(View itemView) {
            super(itemView);
            chip = (Chip) itemView;
        }
    }
}

